package com.makefriends.http;

import android.util.Log;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class VolleyUtil {
    private final String TAG = VolleyUtil.class.getSimpleName() + ">>>>>";

    public interface GetJsonObjectListener {
        void getJsonObject(JSONObject jsonObject, String url);

        void getResponse(String s, String url);

        void error(String tip, String url);

        Map<String, String> getParams(String url);
    }

    public GetJsonObjectListener mGetJsonObjectListener;

    public void setGetJsonObjectListener(GetJsonObjectListener getJsonObjectListener) {
        this.mGetJsonObjectListener = getJsonObjectListener;
    }

    // http://devbean.blog.51cto.com/448512/203501/
    private static class JsonUtilInstance {
        private static final VolleyUtil instance = new VolleyUtil();
    }

    public static VolleyUtil getInstance() {
        return JsonUtilInstance.instance;
    }

    private VolleyUtil() {
    }

    public void getData(final String url) {
        JsonObjectRequest stringRequest = new JsonObjectRequest(url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.e(TAG, ">>>>>>>>>jsonObject:" + jsonObject.toString()); //
                        if (mGetJsonObjectListener != null) {
                            mGetJsonObjectListener.getJsonObject(jsonObject, url);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, "volleyError:" + volleyError.toString());
                        getVolleyError(volleyError, url);
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> map = new HashMap<>();
//                String session = ApplicationWifix.getInstance().getSessionHandler().getSession(url);
//                if (session != null) {
//                    map.put("Cookie", session);
//                }
                return map;
            }

            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                return super.parseNetworkResponse(response);
            }
        };
        // 设置超时重新请求
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(2500, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        // 把请求添加到全局请求队列里面
//        ApplicationWifix.getHttpQueue().add(stringRequest);
    }

    public void sendData(final String url) {
        StringRequest registerRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {//这里是返回正确反馈的接口（只要请求成功反馈的数据都这这里）
                        //数据处理反馈（可以这这里处理服务器返回的数据）
                        Log.e(TAG, ">>>>>>>>>>sendData：" + s);
                        if (mGetJsonObjectListener != null) {
                            mGetJsonObjectListener.getResponse(s, url);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        getVolleyError(volleyError, url);
                        Log.e(TAG, "volleyError:" + volleyError.toString());
                    }
                }) {
            //这里是添加请求头的地方重写了getHeaders() 方法(发送设么请求头要根据自己实际开发需要设定)
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> map = new HashMap<>();
//                String session = ApplicationWifix.getInstance().getSessionHandler().getSession(url);
//                if (session != null) {
//                    map.put("Cookie", session);
//                }
                return map;
            }

            //这里是发送参数的地方，重写了 getParams() 方法（传什么参数给服务器也是实际你自己修改）
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = null;
                if (mGetJsonObjectListener != null) {
                    map = mGetJsonObjectListener.getParams(url);
                }
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    synchronized (response) {
//                        ApplicationWifix.getInstance().getSessionHandler().setSession(response, url);
                    }
                } catch (Exception e) {
                    return Response.error(new ParseError(e));
                }
                return super.parseNetworkResponse(response);
            }

        };

        // 设置超时重新请求
        registerRequest.setRetryPolicy(new
                        DefaultRetryPolicy(2500, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)

        );
//        // 把请求添加到全局请求队列里面
//        ApplicationWifix.getHttpQueue().
//                add(registerRequest);
    }

    private void getVolleyError(VolleyError volleyError, String url) {
        String tip = null;
        //volley 有专门处理error的库，下面就是调用了其中的一些，可以方便调试的时候查找到错误
        Class klass = volleyError.getClass();
        if (klass == com.android.volley.AuthFailureError.class) {
            tip = "未授权，请重新注册";
        } else if (klass == com.android.volley.NetworkError.class) {
            tip = "网络连接错误，请重新注册";
        } else if (klass == com.android.volley.NoConnectionError.class) {
            tip = "无网络连接, 请检查网络";
        } else if (klass == com.android.volley.ServerError.class) {
            tip = "服务器未知错误，请重新注册";
        } else if (klass == com.android.volley.TimeoutError.class) {
            tip = "连接超时，请检查网络";
        }
        //else if (klass == com.android.volley.ParseError.class) {
        //}
        if (mGetJsonObjectListener != null) {
            mGetJsonObjectListener.error(tip, url);
        }
    }
}
